using System;
using System.Collections;
using System.IO;
using UnityEngine;

public class CaptureScreenshot : MonoBehaviour
{
	public int sizeMultiplier = 2;

	public string prefix = "Scale_Screen";

	private int incrementValue;

	private string dateAndTime = "DEFAULT";

	private string screenshotName;

	private string screenshotPath;

	public KeyCode hotkey = KeyCode.P;

	private void Start()
	{
		GeneratePathAndFileName();
	}

	private void GeneratePathAndFileName()
	{
		dateAndTime = DateTime.Today.ToString("d");
		dateAndTime = dateAndTime.Replace("/", "-");
		screenshotName = "/" + prefix + "_" + dateAndTime + "_" + incrementValue;
		screenshotPath = Application.persistentDataPath + screenshotName + ".png";
		CheckForExisting();
	}

	private IEnumerator CheckForExisting()
	{
		do
		{
			UnityEngine.Debug.Log("SCREENSHOT ALREADY EXISTS");
			incrementValue++;
			GeneratePathAndFileName();
			yield return 0;
		}
		while (File.Exists(screenshotPath));
		incrementValue++;
		GeneratePathAndFileName();
	}

	private IEnumerator PrepScreenshot()
	{
		GeneratePathAndFileName();
		while (File.Exists(screenshotPath))
		{
			UnityEngine.Debug.Log("SCREENSHOT ALREADY EXISTS");
			incrementValue++;
			GeneratePathAndFileName();
			yield return 0;
		}
		TakeScreenshot();
	}

	private void TakeScreenshot()
	{
		UnityEngine.Debug.Log(" ------------------ Taking screenshot!" + screenshotPath + " at " + Time.timeSinceLevelLoad);
		SaveScreenshotToFile(screenshotPath);
	}

	public static Texture2D TakeScreenShot()
	{
		return Screenshot();
	}

	private static Texture2D Screenshot()
	{
		int pixelWidth = Camera.main.pixelWidth;
		int pixelHeight = Camera.main.pixelHeight;
		Camera main = Camera.main;
		RenderTexture renderTexture2 = main.targetTexture = new RenderTexture(pixelWidth, pixelHeight, 32);
		Texture2D texture2D = new Texture2D(pixelWidth, pixelHeight, TextureFormat.ARGB32, mipChain: false);
		main.Render();
		RenderTexture.active = renderTexture2;
		texture2D.ReadPixels(new Rect(0f, 0f, pixelWidth, pixelHeight), 0, 0);
		texture2D.Apply();
		main.targetTexture = null;
		RenderTexture.active = null;
		UnityEngine.Object.Destroy(renderTexture2);
		return texture2D;
	}

	public static Texture2D SaveScreenshotToFile(string fileName)
	{
		Texture2D texture2D = Screenshot();
		byte[] bytes = texture2D.EncodeToPNG();
		File.WriteAllBytes(fileName, bytes);
		return texture2D;
	}

	private void Update()
	{
		if (UnityEngine.Input.GetKeyDown(hotkey))
		{
			StartCoroutine(PrepScreenshot());
		}
	}
}
